// pages/courttracks/create/index.js
const app = getApp()
import api from '../../../api/main.js'
import tools from '../../../utils/tools.js'
Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgs: [],
    list: '',
    upload_picture_list: [],
    content:'',
    title:''
  },
  //选择图片方法
  uploadpic: function(e) {
    var that = this //获取上下文
    var upload_picture_list = that.data.upload_picture_list
    //选择图片
    wx.chooseImage({
      count: 9,
      sizeType: ['original'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        var tempFiles = res.tempFiles
        if (upload_picture_list.length + tempFiles.length > 9) {
          wx.showToast({
            title: '对不起，您选择的照片超出限制',
            icon: 'none',
            duration: 2000
          })
          return
        }
        //把选择的图片 添加到集合里
        for (var i in tempFiles) {
          tempFiles[i]['upload_percent'] = 0
          tempFiles[i]['path_server'] = ''
          upload_picture_list.push(tempFiles[i])
        }
        //显示
        that.setData({
          upload_picture_list: upload_picture_list,
        })
        that.uploadimage()
      }
    })
  },
  //点击上传事件
  uploadimage: function() {
    var page = this
    var upload_picture_list = page.data.upload_picture_list
    //循环把图片上传到服务器 并显示进度       
    for (var j in upload_picture_list) {
      if (upload_picture_list[j]['upload_percent'] == 0) {　　　　　　 //调用函数
        upload_file_server(page, upload_picture_list, j)
      }
    }
  },

  // 删除图片
  deleteImg: function(e) {
    let upload_picture_list = this.data.upload_picture_list;
    let index = e.currentTarget.dataset.index;
    upload_picture_list.splice(index, 1);
    this.setData({
      upload_picture_list: upload_picture_list
    });
  }, // 预览图片
  previewImg(e) {
    //获取当前图片的下标
    let index = e.currentTarget.dataset.index;
    //所有图片
    let imgs = this.data.imgs;
    wx.previewImage({
      //当前显示图片
      current: imgs[index],
      //所有图片
      urls: imgs
    })
  },
  formSubmit(e) {
    var that = this
    console.log('form发生了submit事件，携带数据为：', e.detail.value)
    var data = e.detail.value 
    if(!data['title'] && data['title'] == ''){
      wx.showToast({
        title: '请输入动态标题',
        icon:'none',
        duration: 2000
      })
      return
    }
    if(data['title'].length > 40){
      wx.showToast({
        title: '动态标题过长',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if ((!data['content'] && data['content'] == '') || that.data.upload_picture_list.length == 0){
      wx.showToast({
        title: '请输入动态内容获取上传照片',
        icon:'none',
        duration:2000
      })
      return
    }
    var images = []
    for (var i = 0; i < that.data.upload_picture_list.length;i++){
      images.push(that.data.upload_picture_list[i].path)
    }
    data['images'] = images.join(',')
    wx.showLoading({
      title: '正在保存...',
    })
    api.track.saveCourtTrack(data).then(res => {
      wx.hideLoading()
      if (res.code == app.globalData.successCode && res.success) {
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2]; //上一个页面
        prevPage.loadData()
        wx.showModal({
          title: '温馨提示',
          content: '发布动态成功，是否继续发布',
          cancelText:'返回',
          confirmText:'继续',
          success(res) {
            if (res.confirm) {
              that.formReset()
            }else{
              wx.navigateBack()
            }
          }
        })
      }else{
        wx.showToast({
          title: res.msg,
          icon:'none'
        })
      }
      res = null
    })
  },
  formReset() {
    this.setData({
      upload_picture_list:[],imgs:[]
    })
    console.log('form发生了reset事件')
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})

/**
 * 上传图片方法
 */
function upload_file_server(that, upload_picture_list, j) {
  //上传返回值
  const upload_task = wx.uploadFile({
    // 模拟https
    url: app.getUploadServerUrl(), //需要用HTTPS，同时在微信公众平台后台添加服务器地址  
    filePath: upload_picture_list[j]['path'], //上传的文件本地地址    
    name: 'fileData',
    header: {
      'token': app.globalData.token,
      "type": app.globalData.userTypeStr
    },
    formData: {
      'num': j,
      'type': 3,
      'description': '发布动态'
    },
    //附近数据，这里为路径     
    success: function(res) {
      console.log('上传完成')
      var data = JSON.parse(res.data);
      if (data.code == 1 && data.success) {
        upload_picture_list[j]['path'] = data.data.path
        upload_picture_list[j]['path_server'] = app.resourcesFullUrl(data.data.path)
        that.setData({
          upload_picture_list: upload_picture_list
        });
        wx.setStorageSync('imgs', upload_picture_list);
      } else {
        wx.showToast({
          title: data.msg,
          icon: 'none',
          duration: 2000
        })
      }
    }
  })
  //上传 进度方法
  upload_task.onProgressUpdate((res) => {
    upload_picture_list[j]['upload_percent'] = res.progress
    that.setData({
      upload_picture_list: upload_picture_list
    });
  });
}